import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  Modal,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Keyboard,
  PermissionsAndroid,
  Platform,
  Button,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  ImageButton,
  LinearBoardButton,
  LinearButton,
  TextButton,
} from '../../components/Button';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {LinerBoardTextInput} from '../../components/TextInput';
import {NormalHeader} from '../../components/NavigationHeader';
import {getInviteList} from '../../api/user';
import {getAwardList, lottery, getLotteryAwards} from '../../api/award';
import {showToast} from '../../components/Toast';
import {updateUserInfo} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {BASE_API} from '../../config';
import LinearGradient from 'react-native-linear-gradient';
import {ScrollView} from 'react-native-gesture-handler';
import ModalHandler from '../../components/ModalHandler';
import {translate} from 'i18n-js';
import AutoScrollView from '../../components/AutoScrollView';
var moment = require('moment');

class AwardCenterScreen extends BaseComponent {
  constructor(props) {
    super(props);
    this.currentIndex = 0;
    this.CYCLE_TIMES = 30;
    this.uniformTimes = 3;
    // 中奖的奖品序号
    this.luckyOrder = -1;
    this.speed = 100;
    this.noAwardOrder = -1;
    this.state = {
      highLightIndex: -1,
      lotteryModal: false,
      awardRecords: [],
      awards: [],
      luckyAward: {},
      lotteryAmount: 10,
    };
  }

  componentDidMount() {
    this.fetchRecords();
    this.fetchAwards();
  }

  fetchRecords = () => {
    getAwardList({
      page: 1,
      size: 5,
    }).then((resp) => {
      console.log('fetchRecords', JSON.stringify(resp));
      this.setState({
        awardRecords: resp.data.rows,
      });
    });
  };
  fetchAwards = () => {
    getLotteryAwards().then((resp) => {
      console.log('fetchAwards', JSON.stringify(resp));
      let awards = resp.data.rows;
      for (var i = 0; i < awards.length; i++) {
        awards[i].icon =
          awards[i].icon.indexOf('http') == -1
            ? BASE_API + awards[i].icon
            : awards[i].icon;
        if (awards[i].name == 'tryAgain') {
          this.noAwardOrder = i;
        }
      }
      this.setState({
        awards: awards,
      });
    });
  };

  startLottery = () => {
    if (this.isLottering) {
      return;
    }
    this.isLottering = true;
    this.startLotteryAnim();

    lottery({
      userToken: this.props.userInfo.token,
      signin: this.state.lotteryAmount,
    })
      .then((resp) => {
        this.setState({
          luckyAward: resp.data,
        });
        for (var i = 0; i < this.state.awards.length; i++) {
          if (this.state.awards[i].awardId == resp.data.awardId) {
            this.luckyOrder = i;
            break;
          }
        }
        this.fetchRecords();
      })
      .catch((err) => {
        this.luckyOrder = this.noAwardOrder;
        showToast(err.msg);
      });
  };

  startLotteryAnim = () => {
    this.setState(
      {
        highLightIndex: this.currentIndex % 9,
      },
      () => {
        const currentOrder = this.currentIndex % 9;
        this.currentIndex += 1;
        if (
          this.currentIndex > this.CYCLE_TIMES + 8 + this.uniformTimes &&
          this.luckyOrder === currentOrder
        ) {
          clearTimeout(this.lotteryTimer);
          setTimeout(() => {
            // this.stopCallback(LOTTERY_ORDER[this.luckyOrder]);
            setTimeout(() => {
              this.isLottering = false;
              this.currentIndex = 0;
              this.speed = 100;
              this.luckyOrder = -1;
              this.setState({
                lotteryModal: true,
                highLightIndex: -1,
              });
            }, 1000);
          }, 500);
        } else {
          if (this.currentIndex < this.CYCLE_TIMES) {
            this.speed -= 10;
          } else if (
            this.currentIndex > this.CYCLE_TIMES + 8 + this.uniformTimes &&
            this.luckyOrder === currentOrder + 1
          ) {
            this.speed += 80;
          } else if (this.luckyOrder === -1) {
            // 次数超过30次，且尚未拿到抽奖结果时：匀速运动
            this.uniformTimes += 1;
          } else {
            this.speed += 20;
          }
          // 确保速度不能低于 50 ms
          if (this.speed < 50) {
            this.speed = 50;
          }
          this.lotteryTimer = setTimeout(this.startLotteryAnim, this.speed);
        }
      },
    );
  };

  formatTime = (dt) => {
    return moment(dt).format('MM/DD/YYYY');
  };

  renderComponent = () => {
    let awards = this.state.awards;
    let awardRecords = this.state.awardRecords;
    let lotteryAmount = this.state.lotteryAmount;
    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Lottery"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView>
          <View
            style={{
              flexDirection: 'row',
            }}>
            <TouchableOpacity
              style={{
                backgroundColor: '#fff',
                paddingHorizontal: 15,
                paddingVertical: 4,
                borderBottomRightRadius: 20,
                borderTopRightRadius: 20,
              }}
              onPress={() => {
                this.props.navigation.push('AwardRecords');
              }}>
              <Text
                style={{
                  color: '#ab0afa',
                  fontSize: 20,
                }}>
                History
              </Text>
            </TouchableOpacity>
          </View>
          <View
            style={{
              marginTop: 20,
              alignItems: 'center',
              position: 'relative',
            }}>
            <Image
              style={{
                width: 315,
                height: 306,
              }}
              source={require('../../assets/user/lottery_bg.png')}></Image>
            <View
              style={{
                position: 'absolute',
                top: 19,
                left: '50%',
                right: 0,
                width: 270,
                marginLeft: -135,
                alignItems: 'center',
                justifyContent: 'center',
                flexDirection: 'row',
                flexWrap: 'wrap',
              }}>
              {awards.map((item, index) => {
                let row = Math.floor(index / 3);
                let col = index % 3;
                return (
                  <View
                    key={index}
                    style={{
                      width: 90,
                      height: 90,
                      paddingHorizontal: 5,
                      position: 'relative',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}>
                    <Image
                      style={{
                        width: 80,
                        height: 80,
                      }}
                      source={{uri: item.icon}}></Image>
                    {this.state.highLightIndex == index ? (
                      <Image
                        style={{
                          width: 90,
                          height: 90,
                          position: 'absolute',
                          top: 0,
                          left: 0,
                        }}
                        source={require('../../assets/user/lottery_checked.png')}></Image>
                    ) : null}
                  </View>
                );
              })}
            </View>
            <ImageButton
              btnStyle={{
                width: 124,
                height: 38,
              }}
              imageStyle={{
                width: 124,
                height: 38,
              }}
              source={require('../../assets/user/lottery_start.png')}
              onPress={() => {
                this.startLottery();
              }}></ImageButton>
          </View>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingHorizontal: 10,
              width: 360,
              alignSelf: 'center',
            }}>
            <TextButton
              text="10 SIGNIN"
              buttonStyle={{
                backgroundColor: lotteryAmount == 10 ? '#4d0099' : '#ab0afa',
                width: 100,
              }}
              onPress={() => {
                this.setState({
                  lotteryAmount: 10,
                });
              }}></TextButton>
            <TextButton
              text="20 SIGNIN"
              buttonStyle={{
                backgroundColor: lotteryAmount == 20 ? '#4d0099' : '#ab0afa',
                width: 100,
              }}
              onPress={() => {
                this.setState({
                  lotteryAmount: 20,
                });
              }}></TextButton>
            <TextButton
              text="30 SIGNIN"
              buttonStyle={{
                backgroundColor: lotteryAmount == 30 ? '#4d0099' : '#ab0afa',
                width: 100,
              }}
              onPress={() => {
                this.setState({
                  lotteryAmount: 30,
                });
              }}></TextButton>
          </View>
          <View
            style={{
              width: 360,
              alignSelf: 'center',
              marginTop: 20,
              marginBottom: 10,
            }}>
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                paddingHorizontal: 10,
              }}>
              <Text style={{color: '#fff'}}>Winner list</Text>
            </View>
          </View>
          {awardRecords && awardRecords.length > 0 ? (
            <AutoScrollView
              style={{
                width: 360,
                alignSelf: 'center',
                marginTop: 10,
              }}
              delayTime={500}
              height={90}
              startLength={3}
              data={awardRecords}
              scrollHeight={30}
              borderRadius={0}>
              {awardRecords.map((item, index) => {
                return (
                  <View style={{height: 30, paddingVertical: 4}}>
                    <View
                      key={index}
                      style={{
                        backgroundColor: '#ab0afa',
                        marginHorizontal: 30,
                        paddingHorizontal: 15,
                        borderRadius: 100,
                        height: '100%',
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                      }}>
                      <Text style={{color: '#fff'}}>
                        Congrats! {item.userNickName} has won {item.name}
                      </Text>
                      <Text style={{color: '#fff'}}>
                        {this.formatTime(item.createTime)}
                      </Text>
                    </View>
                  </View>
                );
              })}
            </AutoScrollView>
          ) : null}
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
          {/* <View style={{
            flexDirection: 'column',
            alignItems:'center',
            justifyContent:'center',
            paddingHorizontal:30,
            marginTop:40
          }}>
            <Text style={{color:'#fff'}}>Rules</Text>
            <Text style={{color:'#fff',marginTop:4}}>
              The prize you won will be given in your account within 24 hours
            </Text>
          </View> */}
        </ScrollView>

        <Modal
          animationType="fade"
          transparent
          visible={this.state.lotteryModal}>
          <View
            style={{
              justifyContent: 'flex-end',
              flex: 1,
              backgroundColor: 'rgba(151,151,151,0.5)',
            }}>
            <TouchableWithoutFeedback
              onPress={() => {
                this.setState({
                  lotteryModal: false,
                });
              }}>
              <View
                style={{
                  flex: 1,
                  width: '100%',
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  bottom: 0,
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <LinearGradient
                  start={{x: 0, y: 1}}
                  end={{x: 1, y: 1}}
                  colors={['#6601F5', '#CE18EC']}
                  style={{
                    borderRadius: 8,
                    width: 300,
                    padding: 20,
                    flexDirection: 'column',
                    alignItems: 'center',
                  }}>
                  <Text
                    style={{color: '#fff', fontWeight: 'bold', fontSize: 20}}>
                    {this.state.luckyAward.name != 'tryAgain'
                      ? 'Congrats'
                      : 'Sorry'}
                  </Text>
                  {this.state.luckyAward.name != 'tryAgain' ? (
                    <Image
                      source={require('../../assets/user/lottery_congrats.png')}
                      style={{
                        width: 112,
                        height: 153,
                      }}></Image>
                  ) : (
                    <Image
                      source={require('../../assets/user/lottery_sorry.png')}
                      style={{
                        marginTop: 20,
                        width: 100,
                        height: 90,
                      }}></Image>
                  )}

                  <Text style={{color: '#fff', fontSize: 18, marginTop: 10}}>
                    {this.state.luckyAward.detail}
                  </Text>
                  <LinearButton
                    text="Got it"
                    buttonStyle={{
                      backgroundColor: '#FFCB26',
                      width: 160,
                    }}
                    onPress={() => {
                      this.setState({
                        lotteryModal: false,
                      });
                    }}
                  />
                </LinearGradient>
              </View>
            </TouchableWithoutFeedback>
          </View>
        </Modal>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({});

export default connect(mapStateToProps, mapDispatchToProps)(AwardCenterScreen);
